//
//  ViewController.m
//  SmartTank
//
//  Created by Clover on 7/15/17.
//  Copyright © 2017 Clover. All rights reserved.
//


#import "ViewController.h"
#import "YYBlueManger.h"
#import "UIView+Add.h"
#import "UIImage+Add.h"
#import "MBProgressHUD.h"

@interface ViewController ()<YYBlueMangerDelegate>

@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *forwardBtn;
@property (nonatomic, strong) UIButton *rightBtn;
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UIButton *leftBtn;

@property (nonatomic, strong) UIButton *bluetoothBtn;
@property (nonatomic, strong) UIButton *powerBtn;

@property (nonatomic, strong) UIView *greenDot;

@property (nonatomic, assign, getter=isConnected) BOOL connected;
@property (nonatomic, assign, getter=isPowerOn) BOOL powerOn;

@property (nonatomic, copy) NSString *bluetoothName;

@property (nonatomic, strong) NSTimer *connectTimer;
@property (nonatomic, assign) NSInteger counter;
@property (nonatomic, assign) NSInteger connectTimeout;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _bluetoothName = @"raspberrypi";
    _connectTimeout = 10;
    [YYBlueManger sharedManger].delegate = self;
    
    [self setupViews];
    
    [[YYBlueManger sharedManger] addObserver:self forKeyPath:@"connectState" options:NSKeyValueObservingOptionNew context:NULL];
    
    [self updateControlBtnState];
    [self updateBluetoothBtnState];
}

- (void)dealloc {
    [[YYBlueManger sharedManger] removeObserver:self forKeyPath:@"connectState" context:NULL];
}

- (void)setupViews {
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _titleLabel.text = @"SmartTank";
    _titleLabel.font = [UIFont systemFontOfSize:18 weight:1.0];
    [_titleLabel sizeToFit];
    _titleLabel.centerX = self.view.centerX;
    _titleLabel.centerY = 50;
    [self.view addSubview:_titleLabel];
    
    _greenDot = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 8)];
    _greenDot.backgroundColor = [UIColor lightGrayColor];
    _greenDot.centerY = _titleLabel.centerY;
    _greenDot.right = self.view.right - 30;
    _greenDot.layer.cornerRadius = 5;
    [self.view addSubview:_greenDot];
    
    _forwardBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_forwardBtn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [_forwardBtn setBackgroundImage:[UIImage imageWithColor:[UIColor blackColor]] forState:UIControlStateHighlighted];
    [_forwardBtn setTitle:@"前进" forState:UIControlStateNormal];
    [_forwardBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_forwardBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [_forwardBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    _forwardBtn.layer.borderColor = [UIColor blackColor].CGColor;
    _forwardBtn.layer.borderWidth = 0.5;
    [_forwardBtn sizeToFit];
    _forwardBtn.tag = 1001;
    [_forwardBtn addTarget:self action:@selector(controlDownAction:) forControlEvents:UIControlEventTouchDown];
    [_forwardBtn addTarget:self action:@selector(controlUpAction) forControlEvents:UIControlEventTouchUpInside];
    
    _forwardBtn.width += 40;
    _forwardBtn.height += 16;
    _forwardBtn.center = CGPointMake(self.view.centerX, _titleLabel.bottom + 130);
    [self.view addSubview:_forwardBtn];
    
    _leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_leftBtn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [_leftBtn setBackgroundImage:[UIImage imageWithColor:[UIColor blackColor]] forState:UIControlStateHighlighted];
    [_leftBtn setTitle:@"左转" forState:UIControlStateNormal];
    [_leftBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_leftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [_leftBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    _leftBtn.layer.borderColor = [UIColor blackColor].CGColor;
    _leftBtn.layer.borderWidth = 0.5;
    [_leftBtn sizeToFit];
    _leftBtn.tag = 1002;
    [_leftBtn addTarget:self action:@selector(controlDownAction:) forControlEvents:UIControlEventTouchDown];
    [_leftBtn addTarget:self action:@selector(controlUpAction) forControlEvents:UIControlEventTouchUpInside];
    
    _leftBtn.width = _forwardBtn.width;
    _leftBtn.height = _forwardBtn.height;
    _leftBtn.left = self.view.left + 30;
    _leftBtn.top = _forwardBtn.bottom + 40;
    [self.view addSubview:_leftBtn];
    
    _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backBtn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [_backBtn setBackgroundImage:[UIImage imageWithColor:[UIColor blackColor]] forState:UIControlStateHighlighted];
    [_backBtn setTitle:@"后退" forState:UIControlStateNormal];
    [_backBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [_backBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    _backBtn.layer.borderColor = [UIColor blackColor].CGColor;
    _backBtn.layer.borderWidth = 0.5;
    [_backBtn sizeToFit];
    _backBtn.tag = 1003;
    [_backBtn addTarget:self action:@selector(controlDownAction:) forControlEvents:UIControlEventTouchDown];
    [_backBtn addTarget:self action:@selector(controlUpAction) forControlEvents:UIControlEventTouchUpInside];
    
    _backBtn.width = _forwardBtn.width;
    _backBtn.height = _forwardBtn.height;
    _backBtn.centerX = _forwardBtn.centerX;
    _backBtn.top = _leftBtn.bottom + 40;
    [self.view addSubview:_backBtn];
    
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_rightBtn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [_rightBtn setBackgroundImage:[UIImage imageWithColor:[UIColor blackColor]] forState:UIControlStateHighlighted];
    [_rightBtn setTitle:@"右转" forState:UIControlStateNormal];
    [_rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [_rightBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    _rightBtn.layer.borderColor = [UIColor blackColor].CGColor;
    _rightBtn.layer.borderWidth = 0.5;
    [_rightBtn sizeToFit];
    _rightBtn.tag = 1004;
    [_rightBtn addTarget:self action:@selector(controlDownAction:) forControlEvents:UIControlEventTouchDown];
    [_rightBtn addTarget:self action:@selector(controlUpAction) forControlEvents:UIControlEventTouchUpInside];
    
    _rightBtn.width = _forwardBtn.width;
    _rightBtn.height = _forwardBtn.height;
    _rightBtn.right = self.view.right - 30;
    _rightBtn.top = _leftBtn.top;
    [self.view addSubview:_rightBtn];
    
    _bluetoothBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_bluetoothBtn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [_bluetoothBtn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateDisabled];
    [_bluetoothBtn setBackgroundImage:[UIImage imageWithColor:[UIColor blackColor]] forState:UIControlStateHighlighted];
    [_bluetoothBtn setTitle:@"连接蓝牙" forState:UIControlStateNormal];
    [_bluetoothBtn setTitle:@"连接中..." forState:UIControlStateDisabled];
    [_bluetoothBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_bluetoothBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    [_bluetoothBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [_bluetoothBtn addTarget:self action:@selector(connect) forControlEvents:UIControlEventTouchUpInside];
    [_bluetoothBtn sizeToFit];
    _bluetoothBtn.layer.borderColor = [UIColor blackColor].CGColor;
    _bluetoothBtn.layer.borderWidth = 0.5;
    
    _bluetoothBtn.width = self.view.width - 100;
    _bluetoothBtn.height = _forwardBtn.height;
    _bluetoothBtn.centerX = self.view.centerX;
    _bluetoothBtn.bottom = self.view.height - 30;
    [self.view addSubview:_bluetoothBtn];
    
    _powerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _powerBtn.backgroundColor = [UIColor blackColor];
    [_powerBtn setTitle:@"关机" forState:UIControlStateNormal];
    [_powerBtn addTarget:self action:@selector(shutdown) forControlEvents:UIControlEventTouchUpInside];
    [_powerBtn sizeToFit];
    _powerBtn.hidden = YES;
    
    _powerBtn.width += 40;
    _powerBtn.height = _forwardBtn.height;
    _powerBtn.right = self.view.right - 50;
    _powerBtn.top = _bluetoothBtn.top;
    [self.view addSubview:_powerBtn];
    
}

- (void)connect {
    
    if([YYBlueManger sharedManger].managerState == YYBlueManagerStatePoweredOff) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.label.text = @"蓝牙未开启！";
        hud.mode = MBProgressHUDModeText;
        hud.removeFromSuperViewOnHide = YES;
        [hud hideAnimated:YES afterDelay:1.0];
        return;
    }
    
    if([YYBlueManger sharedManger].connectState == YYBlueConnectStateConnected) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确定断开蓝牙连接吗？" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[YYBlueManger sharedManger] cancelPeripheralConnection:nil];
        }]];
        [self presentViewController:alertVC animated:YES completion:nil];
    }else {
        _bluetoothBtn.enabled = self.isConnected;
        [[YYBlueManger sharedManger] scan];
        
        _counter = 0;
        _connectTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
}

- (void)shutdown {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确定关闭系统吗？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSString *str = [NSString stringWithFormat:@"%d", 0x100];
        [[YYBlueManger sharedManger] writeDataToDevice:[str dataUsingEncoding:NSUTF8StringEncoding] writeHandle:nil];
        
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)updateControlBtnState {
    YYBlueConnectState state = [YYBlueManger sharedManger].connectState;
    
    if(state == YYBlueConnectStateDefault ||
       state == YYBlueConnectStateConnecting ||
       state == YYBlueConnectStateCutConnect ||
       state == YYBlueConnectStateFailedConnect) {
        
        _forwardBtn.enabled = NO;
        _leftBtn.enabled = NO;
        _backBtn.enabled = NO;
        _rightBtn.enabled = NO;
    }else if(state == YYBlueConnectStateConnected) {
        
        _forwardBtn.enabled = YES;
        _leftBtn.enabled = YES;
        _backBtn.enabled = YES;
        _rightBtn.enabled = YES;
    }
}

- (void)updateBluetoothBtnState {
    YYBlueConnectState state = [YYBlueManger sharedManger].connectState;
    
    if(state == YYBlueConnectStateDefault ||
       state == YYBlueConnectStateCutConnect ||
       state == YYBlueConnectStateFailedConnect) {
        
        _bluetoothBtn.enabled = YES;
        [_bluetoothBtn setTitle:@"连接蓝牙" forState:UIControlStateNormal];
    }else if(state == YYBlueConnectStateConnecting) {
        
        _bluetoothBtn.enabled = NO;
    }else if(state == YYBlueConnectStateConnected) {
        
        _bluetoothBtn.enabled = YES;
        [_bluetoothBtn setTitle:@"断开蓝牙" forState:UIControlStateNormal];
    }
}

- (void)updateGreenDotState {
    YYBlueConnectState state = [YYBlueManger sharedManger].connectState;
    if(state != YYBlueConnectStateConnected) {
        _greenDot.backgroundColor = [UIColor lightGrayColor];
    }
}

- (void)updatePowerBtnState {
    YYBlueConnectState state = [YYBlueManger sharedManger].connectState;
    if(state == YYBlueConnectStateConnected) {
        _bluetoothBtn.width = self.view.width - _powerBtn.width - 120;
        _powerBtn.hidden = NO;
    }else {
        _bluetoothBtn.width = self.view.width - 100;
        _powerBtn.hidden = YES;
    }
}

- (void)timerAction {
    NSLog(@"counter: %ld", _counter);
    if(_counter >= _connectTimeout) {
        [self cancelTimer];
        
        [[YYBlueManger sharedManger] stop];
        
        [self updateControlBtnState];
        [self updateBluetoothBtnState];
    }else {
        _counter++;
    }
    
}

- (void)cancelTimer {
    if(_connectTimer) {
        [_connectTimer invalidate];
        _connectTimer = nil;
    }
}

- (void)controlDownAction:(UIButton *)sender {
    NSInteger tag = sender.tag;
    
    int b = 0x00;
    if(tag == 1001) {
        b = 0x20; //前进
    }else if(tag == 1002) {
        b = 0x30; //左转
    }else if(tag == 1003) {
        b = 0x40; //后退
    }else if(tag == 1004) {
        b = 0x50; //右转
    }
    
    NSString *str = [NSString stringWithFormat:@"%d", b];
    
    [[YYBlueManger sharedManger] writeDataToDevice:[str dataUsingEncoding:NSUTF8StringEncoding] writeHandle:nil];
}

- (void)controlUpAction {
    int b = 0x10;
    NSString *str = [NSString stringWithFormat:@"%d", b];
    [[YYBlueManger sharedManger] writeDataToDevice:[str dataUsingEncoding:NSUTF8StringEncoding] writeHandle:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if([keyPath isEqualToString:@"connectState"]) {
        [self updateControlBtnState];
        [self updateBluetoothBtnState];
        [self updateGreenDotState];
        [self updatePowerBtnState];
    }
}

#pragma mark - YYBlueManagerDelegate
- (void)blueManagerblescanBluDevice:(YYBlueManger *)manager andTheDevice:(CBPeripheral *)peripheral {
    if([peripheral.name isEqualToString:_bluetoothName]) {
        [[YYBlueManger sharedManger] connect:peripheral orTheDeviceName:nil];
    }
}

- (void)blueManagerdidConnectSuccees:(YYBlueManger *)manager peripheral:(CBPeripheral *)peripheral {
    
    [self cancelTimer];
    
    NSLog(@"%@", @"connected!");
}

- (void)blueManagerFailedConnect:(YYBlueManger *)manager peripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    
    [self cancelTimer];
    
    NSLog(@"%@", @"connect error!");
}

- (void)blueManagerCutConnect:(YYBlueManger *)manager peripheral:(CBPeripheral *)peripheral error:(NSError *)error {

    [self cancelTimer];
    
    NSLog(@"%@", @"disconnected!");
}

- (NSArray *)blueManagerServerAdrres:(YYBlueManger *)manager peripheral:(CBPeripheral *)peripheral {
    NSArray<CBService *> *services = peripheral.services;
    if(services.count) {
        CBService *service = services.firstObject;
        return @[service.UUID.UUIDString];
    }
    return nil;
}

- (NSDictionary *)blueManagerCharacteristicsAdrres:(YYBlueManger *)manager peripheral:(CBPeripheral *)peripheral {
    NSArray<CBService *> *services = peripheral.services;
    if(services.count) {
        CBService *service = services.firstObject;
        NSArray<CBCharacteristic *> *characteristics = service.characteristics;
        if(characteristics.count) {
            CBCharacteristic *characteristic = characteristics.firstObject;
            return @{BlueCharacteristicWrite: characteristic.UUID.UUIDString,
                     BlueCharacteristicRead: characteristic.UUID.UUIDString};
        }
    }
    return nil;
}

- (void)blueManagerblereceiveData:(YYBlueManger *)manager andTheData:(NSData *)data {
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"received: %@", str);
    
    NSInteger counter = [str integerValue];
    _greenDot.backgroundColor = (counter % 2) ? [UIColor greenColor] : [UIColor lightGrayColor];
}

- (void)blueManagerFailedState:(YYBlueManger *)manager statu:(YYBlueManagerState)statu {
    if(statu == YYBlueManagerStatePoweredOff) {
        
    }
}


@end
